package com.example.admin.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;

public class MyService extends Service implements Runnable {
    private String TAG = this.getClass().getSimpleName();
    private volatile boolean flag = true;
    private Thread thread = new Thread(this);

    public MyService() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().post(new SimpleEvent("service created"));
        Log.i(TAG, "onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand()");
        EventBus.getDefault().post(new SimpleEvent("service started"));
        if(!thread.isAlive()){
            thread.start();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy()");
        flag = false;//防止service内存泄漏
        thread.interrupt();//立即中断休眠的线程
        super.onDestroy();
        EventBus.getDefault().post(new SimpleEvent("service destroyed"));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind()");
        EventBus.getDefault().post(new SimpleEvent("service onBind"));
        if(!thread.isAlive()){
            thread.start();
        }
        return new MyBinder();
    }

    @Override
    public void onLowMemory() {
        Log.i(TAG, "onLowMemory()");
        super.onLowMemory();
    }

    @Override
    public void run() {
        int i = 0;
        try {
            while (flag) {
                Thread.sleep(1000);
                EventBus.getDefault().post(new SimpleEvent("service alive:" + i));
                i++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public class MyBinder extends IMyAidlInterface.Stub {

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public void sendMsg(String msg) throws RemoteException {
            Log.i(TAG, "getMsg:" + msg);
        }

    }
}
